#include <memory>

#include "compile_run.hpp"
#include "../common/httplib.h"
#include "../RPC/source/server/rpc_server.hpp"
#include "../RPC/source/common/json.hpp"

void usage(const std::string &process)
{
    std::cout << "Usage: " << "\n\t" << process << " port" << std::endl;
}

void compile_run(const Json::Value &in_val, Json::Value &out_val)
{
    // 序列化in_val
    std::string in_json;
    JsonMuduoRPC::JSON::serialize(in_val, in_json);

    // 进行判题
    std::string out_json;
    oj_compile_and_run::CompileAndRun::start(in_json, out_json);

    // 反序列化out_json
    JsonMuduoRPC::JSON::unserialize(out_json, out_val);
}

// ./compile_server port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        usage(argv[0]);
        return 1;
    }

    uint16_t port = std::stoi(argv[1]);

    // RPC版
    JsonMuduoRPC::server::RPCServer::ptr server =
        std::make_unique<JsonMuduoRPC::server::RPCServer>(
            JsonMuduoRPC::Address("127.0.0.1", port), true, JsonMuduoRPC::Address("127.0.0.1", 9090));

    // 0. 构建服务描述
    JsonMuduoRPC::server::ServiceDescribeFactory service_factory;
    service_factory.setParamsDescribe("code", JsonMuduoRPC::server::VType::STRING);
    service_factory.setParamsDescribe("input", JsonMuduoRPC::server::VType::STRING);
    service_factory.setParamsDescribe("cpu_limit", JsonMuduoRPC::server::VType::INTEGRAL);
    service_factory.setParamsDescribe("mem_limit", JsonMuduoRPC::server::VType::INTEGRAL);
    service_factory.setResultType(JsonMuduoRPC::server::VType::OBJECT);
    service_factory.setServiceCallBack(compile_run);
    service_factory.setServiceName("compile_run");

    server->registryMethod(service_factory.bulid());

    server->start();

    // httplib::Server server;

    // //注册一个方法
    // //针对当用户以post的方式请求/compile_run时触发
    // server.Post("/compile_run", [](const httplib::Request& request, httplib::Response& response){
    //     //规定收到的HTTP请求的正文部分就是组织好的json串
    //     std::string in_json = request.body;
    //     std::string out_json;
    //     if (in_json.size() != 0)
    //     {
    //         oj_compile_and_run::CompileAndRun::start(in_json, out_json);
    //         response.set_content(out_json, "application/json;charset=utf-8");
    //     }

    // });
    // server.listen("0.0.0.0", port); //启动http服务

    return 0;
}
